<template>
  <div class="work-order-list">
    <CommonHeader title="简单生产领料单" :is-show-back="false" class="header-top"></CommonHeader>
    <div class="search-box">
      <van-search v-model="inputStr" show-action @search="searchEvent" placeholder="请输入单据编号">
        <template #action>
          <van-button type="info" size="small" @click="searchEvent">搜索</van-button>
        </template>
      </van-search>
    </div>
    <div style="display:flex">
      <van-tabs @click="changeTab" v-model="searchParams.state" color="#548AF1" style=" width: 100%;">
        <van-tab v-for="(tab, index) in tabs" :key="index" :name="tab.state" :title="tab.title"></van-tab>
      </van-tabs>
    </div>
    <CommonMain>
      <template>
        <van-pull-refresh v-model="refreshing" :disabled="isRefreshDisable" @refresh="onRefresh">
          <van-list v-if="list.length > 0" v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :immediate-check="false">
            <listItem v-for="(item, index) in list" :key="index" :item-obj="item" @toEdit="toEdit(item)">
              <template slot="buttonGorup">
                <div class="btn btn-01" v-if="item.state === 1" @click="handleComplete(item,2)">完成</div>
                <div class="btn btn-01" v-if="item.state === 0" @click="handleComplete(item, 1)">生效</div>
                <div class="btn btn-01" v-if="item.state === 2" @click="handleComplete(item, 3)">关闭</div>
              </template>
            </listItem>
          </van-list>
          <div v-if="!loading && this.list.length == 0" class="no-data">暂无数据</div>
        </van-pull-refresh>
      </template>
    </CommonMain>
    <van-dialog v-model="show" title="确认" className="sure-dialog"  show-cancel-button confirmButtonColor="#3C76FF" @confirm="submitComplete">
      <div class="model-content">
        <div class="name" v-if="state==2">是否完成入库单：</div>
        <div class="name" v-if="state==4">是否取消入库单：</div>
        <div class="name" v-if="state==1">是否生效入库单：</div>
        <div class="name" v-if="state==3">是否关闭入库单：</div>
        <div class="value">{{ completeData.orderNumber }}</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <van-button round block type="primary" @click="submitComplete">确认</van-button>
      </div>
    </van-dialog>
    <img src="@/assets/images/allocation/scan.png"  v-draggable  class="scan-img" @click="scanCodeEvent"/>
  </div>
</template>

<script>
import listItem from './components/listItem.vue';
import CommonHeader from '@/components/CommonHeader/index.vue';
import CommonMain from '@/components/CommonMain/index.vue';
import { productionSelect} from '@/api/allocation';
import { stateChange, getList ,getScanList ,scanCodeRuleGet,purchaseCheckInQuantity} from '@/api/inventory';
import { removeBarCodePurchaseStocks } from '@/api/purchase';
import Toasts from '@/components/Toast'
import SearchForm from './components/SearchForm.vue';
import { handleScanData } from '@/utils/common';
import Vue from 'vue';
import { Dialog,Toast ,Tab, Tabs,Search, Button} from 'vant';
Vue.use(Dialog);
Vue.use(Toast);
Vue.use(Search);
Vue.use(Button);
import { queryRepositoriesIsolationList, queryAllWareHoseList } from '@/api/allocation';
import { reqWareHouseInfo, reqProductionMaterialList } from "@/api/productionMaterialRequest.js";
export default {
  components: {
    CommonHeader,
    CommonMain,
    listItem,
    SearchForm,
    Toasts,
    [Dialog.Component.name]: Dialog.Component,
    [Tab.name]: Tab,
    [Tabs.name]: Tabs,
  },
  data () {
    return {
      businessUnitCode:'',
      drawer:false,
      loading: false,
      list: [],
      searchParams: {
        state:'1',
        typeCode: 'purchase', //类型（生产入库：workOrderComplete 生产退料入库：applicationReturn 采购入库：purchase）
        compositeSearch: '', //综合搜索
        isInputType: true, //isInputType 为true --入库单  false-- 出库单
        pdaList: 1,
        current: 1,
        size: 10,
        warehouseCode:""
      },
      refreshing: false,
      finished: false, // 列表
      // ---------------------------------------
      total: 0,
      //   搜索组件
      searchFlag: false,
      search: '',
      //   扫码提示弹框
      isShowConfirmDialog: false,
      // 滚动与下拉冲突
      scrollTop: 0,
      isRefreshDisable: false,
      isRequest:false,
      // 完成弹窗
      show: false,
      completeData: {},
      warehouseOptions:[],//仓库列表
      tabs: [
        {
          title: '全部',
          state: '',
          code: '1,2',
          status: [1,2]
        },
        {
          title: '生效',
          state: '1',
          code: '1'
        },
        {
          title: '完成',
          state: '2',
          code: '2'
        },
      ],
      scanParams:{
      },
      state:0,
      inputStr:""  //搜索输入框内容
    }
  },
  watch: {
    scrollTop (newval) {
      if (newval > 0) {
        this.isRefreshDisable = true
      } else {
        this.isRefreshDisable = false
      }
    }
  },
  created(){
    document.title = "简单生产领料单";
  },
  mounted(){
    this.getList();
    reqProductionMaterialList();
    reqWareHouseInfo();
  },
  methods: {
    businessUnitCodeClick(item){
      this.businessUnitCode = item.businessUnitCode;
      let data = JSON.parse(localStorage.getItem('businessUnitCodeStorApp') ||'{}')
      data['com.yelink.purchaseWarehousing.com'] = item.businessUnitCode
      localStorage.setItem('businessUnitCodeStorApp' , JSON.stringify(data))
      this.drawer=false;
      this.onRefresh();
    },
    clear() {
      this.scanParams.scanCode = ""
      this.$refs.SearchForm.cancel();
    },
    changeTab(name,title){
      if(name === ''){
        this.searchParams.status = '1,2'
      }else{
        delete this.searchParams.status
      }
      this.onRefresh('tabChange')
    },
    handleWarehouseCodeChange(){
      localStorage.setItem('home-purchase-warehouseCode',this.searchParams.warehouseCode)
      this.onRefresh('init');
    },
    // 获取所有的仓库列表
    async getAllWarehouse () {
      const result = await queryAllWareHoseList()
      const { code, data = {}, message } = result.data || {}
      if (+code === 200) {
        const { records = [] } = data
        this.warehouseOptions = records
        if(!localStorage.getItem('home-purchase-warehouseCode')){
          this.searchParams.warehouseCode = "";
          localStorage.setItem('home-purchase-warehouseCode',this.searchParams.warehouseCode)
        }else{
          this.searchParams.warehouseCode = localStorage.getItem('home-purchase-warehouseCode');
        }
        this.onRefresh('init')
      } else {
        Toast(message)
      }
    },
    async scanHomeBarcodeTrackWithoutNumber(res) {
      const that = this;
      res = await this.scanCodeRuleGet(res);
      if (this.loading) {
        return;
      }
      this.scanParams.scanCode = res
      this.onRefresh('scan')
    },
    // 播放音频
    playAudio(isSuccess) {
      // const audioElement = document.getElementById('audio')
      const audioElement = this.$refs.audio;
      // audioElement
      audioElement.src = isSuccess
        ? require("@/assets/audio/正确.mp3")
        : require("@/assets/audio/错误.mp3");
      this.$nextTick(() => {
        try {
          audioElement.paused && audioElement.play();
        } catch (error) {
          console.log(error);
        }
      });
    },
    // 解码 refund-outbound-app.material-out.handleScanCode.barCode
    async scanCodeRuleGet(scanCode) {
      try {
        const params = {
          code: "refund-outbound-app.material-out.handleScanCode.barCode",
        };
        const {
          data: { code, data },
        } = await scanCodeRuleGet(params);

        if (code === "200") {
          // 如果有配置解码规则
          if (data.value) {
            const fn = new Function(`return ${data.value}`)();
            const result = fn(scanCode);
            //   this.playAudio(true);
            return result;
          } else {
            //  this.playAudio(true);
            return scanCode;
          }
        }
      } catch (error) {
        this.playAudio(false);
        return "";
      }
    },
    // 手动拉起相机
    scanChange(){
      const that = this
      if(process.env.NODE_ENV === 'development'){
        // this.handleScanData("PO20230611002")
        that.$nextTick(()=>{
          that.$refs.searchSelect.blur()
        })
        that.scanHomeBarcodeTrackWithoutNumber('20240226-CGSH0550')
      }else{
        window.flutter_inappwebview.callHandler("qrCode").then((res) => {
          if (res) {
            that.$nextTick(()=>{
              that.$refs.searchSelect.blur()
            })
            that.scanHomeBarcodeTrackWithoutNumber(res)
          }
        });
      }

    },
    // 下拉刷新
    onRefresh (type = 'onRefresh') {
      // 清空列表数据
      this.finished = false
      this.list = []
      this.searchParams.current = 1
       if(type == 'scan'){
        this.getSearch()
      }else{
        this.getList(type)
      }
    },
    scanOperate(){
      if(this.list.length == 0){//查询结果为空提示
          Toast({
            className:"myToast jinggao",
            message: '暂无数据',
            position: 'top',
          });

        }else if(this.list.length == 1){//查询结果为一条则跳转
          this.$router.push({
            path:'/allocationDetail',
            query:{
              id:this.list[0].id,
              orderNo:this.list[0].orderNumber
            }
          })
        }
    },
    async getSearch(){
      this.loading = true
      this.refreshing = true
      const params = {
        warehouseCode:this.searchParams.warehouseCode,
        scanCode : this.scanParams.scanCode,
        inOrOutTypes:"purchase"
      }
      const result = await getScanList(params)
      this.refreshing = false
      this.loading = false
      const { code, data = {},message} = result.data || {}
      if (code == '200') {
        if(data.list && data.list.length > 0) {
          data.list.forEach(item => {
            item.isToggle = false
          })
        }
        this.searchParams.state = ''//切换至全部显示
        this.list = data.list||[]
        this.scanOperate()
        this.finished = true
      }else{
        Toast.fail(message)
      }
    },
    async getList (type) {
      this.loading = true;
      this.refreshing = true;
      const result = await getList(this.searchParams)
      this.refreshing = false
      this.loading = false
      const { code, data = {}} = result.data || {}
      if (code == '200') {
        if(data.records && data.records.length > 0) {
          data.records.forEach(item => {
            item.isToggle = false
          })
        }
        if (this.searchParams.current > 1) {
          this.list = this.list.concat(data.records)
        } else {
          this.list = data.records
        }
        this.total = data.total
        this.tabs[0].title = `全部(${data.dto[1] + data.dto[2]})`
        for (const key in data.dto) {
          const index = this.tabs.findIndex(tab => tab.code === key)
          //console.log('index',index)
          if (index > -1) {
            switch (key) {
              case '1':
                this.tabs[index].title = `生效(${data.dto[key]})`
                break
              case '2':
                this.tabs[index].title = `完成(${data.dto[key]})`
                break
              default:
                break
            }
          }
        }
        if (type !== 'tabChange' ) {
          if(type != 'init'){
            if(this.list.length == 1){//查询结果为一条则跳转
              this.$router.push({
                path:'/allocationDetail',
                query:{
                  id:this.list[0].id,
                  orderNo:this.list[0].orderNumber
                }
              })
            }
          }
        }
        if (this.total <= this.list.length || data.records.length==0 || data.records.length < this.searchParams.size) {
          this.finished = true;
        }
      } else {
        Toast.fail('系统繁忙');
      }
    },
    // 确认搜索
    handleConfirmSearch (val) {
      // this.searchParams = val
      let detaultParams = {current:this.searchParams.current,size:this.searchParams.size,typeCode: 'purchase',isInputType: true, pdaList: 1}
      this.searchParams = {...detaultParams,...val}
      this.searchParams.state=''
      delete this.searchParams.state
      this.searchParams.status = '1,2'
      this.searchFlag = false
      this.onRefresh('searchByQueryParams')
    },
    // 重置搜索
    handleCancelSearch (val) {
      let detaultParams = {current:this.searchParams.current,size:this.searchParams.size,typeCode: 'purchase',isInputType: true, pdaList: 1}
      console.log(this.searchParams, '====')
      this.searchParams = {...detaultParams,...val}
      this.searchParams.state= '1'
      this.searchParams.warehouseCode = ""
      delete this.searchParams.status
      this.searchFlag = false
      localStorage.removeItem('home-purchase-warehouseCode')
      this.onRefresh('searchByQueryParams')
    },
    // 弹出搜索框
    showSearch () {
      this.searchFlag = !this.searchFlag
    },
    // 搜索
    onSearch() {
      console.log(this.search)
    },
    // 取消搜索
    onCancel() {
      this.searchFlag = false
    },
    // 加载更多
    onLoad () {
      if(this.finished){
        return
      }
      console.log('滚到了底部')
      this.searchParams.current += 1
      this.getList()
    },
    async handleScanData (val) {
      if(this.isRequest){
        return
      }
      this.isRequest = true
      setTimeout(()=>{
        this.isRequest = false
      },100)
      const res = await productionSelect(val);
      let { data } = res;
      // console.log(JSON.stringify(data.data));
      if (data.code == 200) {
        data.data = {...data.data,...data.data.materialFields.skuEntity}
        data.data.materialFields.skuId = data.data.skuId
        data.data.materialFields.skuEntity = {...data.data.materialFields.skuEntity}
        data.data.materialFields.skuEntity.skuId = data.data.materialFields.skuEntity.skuId ? data.data.materialFields.skuEntity.skuId :data.data.skuId
        let params = encodeURIComponent(JSON.stringify(data.data))
        this.$router.push('/allocationDetail?type=scan&data='+params)
      } else {
        Dialog.alert({
          title:"扫码提示",
          message:res.data.message,
          confirmButtonColor: "#548AF1",
          showCancelButton:false
        })
      }
    },
    // 状态改变
    async changeState(item, state) {
      if(state == 2){
        const params = {
          inOrOutType:item.item,
          id:item.id,
          orderNumber:item.orderNumber,
          relateOrders:item.relateOrders,
          relateType:item.relateType,
          state:2
        }
        this.purchaseCheckInQuantity(params,item,state)
        return
      }
      await this.stateChange(item,state)
    },
    async stateChange(item,state){
      const res = await stateChange({ id: item.id, inOrOutType: item.inOrOutType, state})
      let { data } = res;
      if (data.code == 200) {
        Toast.success('状态更改成功')
        if(state == 3 || state == 4){
          // 将批次删除
          const deleteBar = await removeBarCodePurchaseStocks({relateNumber: item.orderNumber})
        }
        this.onRefresh('searchByQueryParams')
      } else {
        Toast(data.message)
      }
    },
    //入库校验
    async purchaseCheckInQuantity(params,item,state) {
      const result = await purchaseCheckInQuantity(params)
      const { code, message, data } = result.data
      if (code == 200) {
        if (data.type == 1) {
          Dialog.confirm({
            title: "提示",
            message: data.remind+',确认是否提交',
            confirmButtonColor: "#548AF1",
          }).then(async () => {
            await this.stateChange(item,state)
          }).catch(() => {
            // on cancel
          });

        } else if (data.type == 2) {
          Toast.fail(data.remind)
        } else {
          await this.stateChange(item,state)
        }
      } else {
        Toast.fail(message)
        throw new Error()
      }
    },
    // 完成确认
    submitComplete() {
      this.show = false
      console.log(this.completeData, '==89')
      this.changeState(this.completeData,  this.state)
    },
    // 打开完成确认弹窗
    handleComplete(item,state) {
      this.show = true
      this.state = state
      this.completeData = item
    },
    add() {
      // this.$router.push('/allocation/add')
      this.$router.push('/allocation/addIndex')
    },
    toEdit(item){
      return;
      // this.$router.push('/allocationDetail?info' + JSON.stringify(item))
      this.$router.push({
        path:"/allocationDetail",
        query:{
          id:item.id,
          orderNo:item.orderNumber
        }
      })
    },
    searchEvent(){
      const str = this.inputStr;
      console.log('搜索内容',str);
    },
    //扫码
    async scanCodeEvent(){
      try {
        const res = await window.flutter_inappwebview.callHandler('qrCode');
        this.inputStr = res;
        this.searchEvent();
        console.log('调用精致提供的扫码api',res);
      } catch (error) {
        console.log("调用精致提供的扫码api",error);
      }
    }
  }
}
</script>
<style lang="scss" scoped>
@import '../../assets/css/common.scss';
.right-icon {
  display: flex;
  align-items: center;
}
.scan-img{
  position: fixed;
  bottom: 1vh;
  right: 0;
  // transform: translateX(-50%);
  width: 82px;
  height: 82px;
  z-index: 2;
}
.work-order-list {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  .search-box{
    ::v-deep .van-search__action{
      line-height: 0 !important;
    }
  }
  .van-pull-refresh {
    height: 100%;
    overflow: scroll;
    /deep/ .van-pull-refresh__track {
      // overflow: scroll;
    }
    .van-list {
      height: 100%;
      // overflow: scroll;
    }
    .no-data {
      height: 100%;
      font-size: 14px;
      display: flex;
      justify-content: center;
      color: #c7c6c6;
      padding-top: 30px;
    }
  }
}
.sure-dialog{
  border-radius: 4px;
}
.model-content{
  padding: 25px 10px 20px 26px;
  .name{
    font-size: 14px;
    color: #666666;
  }
  .value{
    font-size: 16px;
    color: #548AF1;
    margin-top: 10px;
  }
}
.shaixuan{
  width: 80px;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  padding: 0 4px;
  color: #646566;
  font-size: 14px;
  line-height: 20px;
  cursor: pointer;
  background: #fff;
}
</style>